/*
** client_ftp.c for ftp in /home/morgan_t/Documents/svn-for-my-proj/tek2/UNIX/my_ftp
** 
** Made by thomas morgant
** Login   <morgan_t@epitech.net>
** 
** Started on  Tue Apr  3 17:16:27 2012 thomas morgant
** Last update Sun Apr  8 15:33:47 2012 thomas morgant
*/

#include "ftp.h"

int	my_strlen(char *str)
{
  int	i = 0;

  while (str[i])
    i++;
  return (i);
}

void	parse_cmd(char *buf)
{
  char	**cmd;

  cmd = str_to_wordtab(buf, ' ');
  if (!strncmp(cmd[0], "ls", 2))
    system("/bin/ls --color");
  else if (!strncmp(cmd[0], "pwd", 3))
    printf("%s\n", getenv("PWD"));
  else if (!strncmp(cmd[0], "quit", 4))
    exit(EXIT_SUCCESS);
  else if (!strncmp(cmd[0], "pwd", 3))
    printf("%s\n", getenv("PWD"));
  else if (!strncmp(cmd[0], "pwd", 3))
    printf("%s\n", getenv("PWD"));
}

void	launch_client()
{
  char	*cmd;

  cmd = malloc(sizeof(cmd));
  write(1, "my_ftp $ ", 10);
  while (fgets(cmd, sizeof(cmd), stdin))
    {
      parse_cmd(cmd);
      write(1, "my_ftp $ ", 10);
    }
}

int	init_client(char *host, int port)
{
  SOCK		sock;
  t_socket_in	sin;

  sock = socket(AF_INET, SOCK_STREAM, 0);
  sin.sin_addr.s_addr = inet_addr(host);
  sin.sin_family = AF_INET;
  sin.sin_port = htons(port);
  if (connect(sock, (t_socket *)&sin, sizeof(sin)) == SOCKET_ERROR)
    {
      printf("Impossible de se connecter\n");
      exit(EXIT_FAILURE); 
    }
  printf("Connexion au serveur!\n");
  launch_client();
  closesocket(sock);
  return (EXIT_SUCCESS);
}

int	main(int ac, char **av)
{
  char	*host;
  int	port;

  if (ac < 3)
    {
      fprintf(stderr, "Usage: %s [host] [port]\n", av[0]);
      exit(EXIT_FAILURE);
    }
  port = atoi(av[2]);
  host = (av[1]);
  init_client(host, port);
  return (EXIT_SUCCESS);
}
